package com.das.mechanic_base.mvp.view.processnew;

import android.Manifest;
import android.annotation.SuppressLint;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.das.mechanic_base.R;
import com.das.mechanic_base.R2;
import com.das.mechanic_base.adapter.processnew.ConstructionProcessAdapter;
import com.das.mechanic_base.adapter.processnew.NewProcessShowAdapter;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.base.X3BaseActivity;
import com.das.mechanic_base.bean.alone.AloneImageAndRecordBean;
import com.das.mechanic_base.bean.camera.CameraBean;
import com.das.mechanic_base.bean.common.AwsFileBean;
import com.das.mechanic_base.bean.custrecord.AloneDetectionBean;
import com.das.mechanic_base.bean.processsive.ProcessNewBean;
import com.das.mechanic_base.bean.processsive.ProcessSiveTempLetBean;
import com.das.mechanic_base.bean.processsive.ProgressListBean;
import com.das.mechanic_base.def.alone.AloneUploadStatus;
import com.das.mechanic_base.gen.DaoSessionUtils;
import com.das.mechanic_base.gen.WorkNewImageBean;
import com.das.mechanic_base.mvp.contract.process.NewProcessNewContract;
import com.das.mechanic_base.mvp.presenter.process.NewProcessNewPrestener;
import com.das.mechanic_base.utils.FusedLocationUtils;
import com.das.mechanic_base.utils.SpHelper;
import com.das.mechanic_base.utils.X3AloneLayoutUtils;
import com.das.mechanic_base.utils.X3StatusBarUtil;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3ToastUtils;
import com.das.mechanic_base.utils.X3Utils;
import com.das.mechanic_base.widget.X3BottomAloneImageDialog;
import com.das.mechanic_base.widget.X3BottomAloneImageNumDialog;
import com.das.mechanic_base.widget.X3BottomInputProcessNameDialog;
import com.das.mechanic_base.widget.X3PointDialog;
import com.das.mechanic_base.widget.X3SelectPhotoDialog;
import com.das.mechanic_base.widget.X3SwipeBackLayout;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.kyleduo.switchbutton.SwitchButton;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import razerdp.basepopup.BasePopupWindow;

public class X3NewProcessShowNewActivity extends X3BaseActivity<NewProcessNewPrestener> implements NewProcessNewContract.View, NewProcessShowAdapter.IOnClickTake, NewProcessShowAdapter.IOnClickPlan, X3BottomAloneImageDialog.IOnClickAloneImage, X3BottomAloneImageNumDialog.IOnSelectImage, FusedLocationUtils.IOnGetLocation, View.OnClickListener, CompoundButton.OnCheckedChangeListener, NewProcessShowAdapter.IOnClickCustomProcess, X3BottomInputProcessNameDialog.IOnClickOk, ConstructionProcessAdapter.IOnClickTitle {

    @BindView(R2.id.tv_title)
    TextView tv_title;
    @BindView(R2.id.iv_back)
    ImageView iv_back;
    @BindView(R2.id.rlv_work)
    RecyclerView rlv_work;
    @BindView(R2.id.rl_header)
    RelativeLayout rl_header;
    @BindView(R2.id.btn_commit)
    Button btn_commit;
    @BindView(R2.id.sbl_view)
    X3SwipeBackLayout sbl_view;
    @BindView(R2.id.sb_set)
    SwitchButton sb_set;

    // 是否显示必填选项
    private boolean isShowRequired = true;

    private boolean isChange = false;//记录是否编辑了

    private NewProcessShowAdapter processAdapter;

    private X3BottomAloneImageDialog aloneImageDialog;

    private ProcessSiveTempLetBean workBean;
    private X3PointDialog backDialog;
    private X3PointDialog deleteProcessDialog;
    private List<String> serviceBaseSnList;
    private String imageName;
    private X3SelectPhotoDialog photoDialog;
    private int titleIndex,imageIndex;
    private X3BottomAloneImageNumDialog numDialog;
    private long carId;
    private LinearLayoutManager linearLayoutManager;
    private FusedLocationUtils fusedLocationUtils;
    private String title;
    private ProcessNewBean mainBean;
    private boolean standardOrNot; //true  标准的  false  自定义的工序
    private long leftPhotoAmount;
    private String workingProcedureName;
    private X3AloneLayoutUtils layoutUtils;
    private X3PointDialog delDialog;

    @Override
    protected int getLayoutId() {
        EventBus.getDefault().register(this);
        return R.layout.x3_activity_new_process_show_new;
    }

    @Override
    protected NewProcessNewPrestener createPresenter() {
        return new NewProcessNewPrestener();
    }

    @Override
    protected void initView() {
        layoutUtils = new X3AloneLayoutUtils(this);
        X3StatusBarUtil.darkMode(this);
        rl_header.setPadding(0, X3StatusBarUtil.getStatusBarHeight(this),0,0);
        swipeBackLayout.setEnableGesture(false);

        fusedLocationUtils = new FusedLocationUtils(this);
        fusedLocationUtils.setiOnGetLocation(this);
        btn_commit.setOnClickListener(this);
        sb_set.setOnCheckedChangeListener(this);

        sbl_view.setIsBackToEnd(true);
        sbl_view.setSwipeBackListener(new X3SwipeBackLayout.OnSwipeBackListener() {
            @Override
            public void onViewPositionChanged(View mView, float swipeBackFraction, float swipeBackFactor) {

            }

            @Override
            public void onViewSwipeFinished(View mView, boolean isEnd) {
                if(isEnd){
                    Log.e("SSSS","onViewSwipeFinished");
                    finish();
                }
            }

            @Override
            public void onViewBack() {
                // 下拉弹回
                if(isChange){
                    showDilog();
                }else {
                    onViewSwipeFinished(sbl_view,true);
                }
            }
        });


        initRecyce();
        requestAll();
    }


    @Override
    public boolean isTransparent() {
        return true;
    }

    private void requestAll() {
        workBean = (ProcessSiveTempLetBean) getIntent().getSerializableExtra("workBean");

        standardOrNot = workBean.standardOrNot;
        leftPhotoAmount = workBean.leftPhotoAmount;
        tv_title.setText(workBean.name);
        serviceBaseSnList = workBean.serviceBaseSnList;
        workingProcedureName = workBean.name;
        carId = getIntent().getLongExtra("carId", 0L);

        if(mPresenter != null){
            mPresenter.getWorkProceudreInfoByWorkBaseIdAndTechnicSn(serviceBaseSnList.toArray(new String[serviceBaseSnList.size()]),workBean.sn,providerId());
        }

        btn_commit.setText((leftPhotoAmount > 0) ? getString(R.string.re_submit) : getString(R.string.x3_btn_submit));
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initRecyce() {
        linearLayoutManager = new LinearLayoutManager(this);
        rlv_work.setLayoutManager(linearLayoutManager);
        processAdapter = new NewProcessShowAdapter(this);
        rlv_work.setAdapter(processAdapter);
        processAdapter.setiOnClickTake(this);
        processAdapter.setiOnClickPlan(this);
        processAdapter.setIOnClickCustomProcess(this);
        processAdapter.setIOnClickTitle(this);

    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, 0);
    }


    @OnClick({R2.id.iv_back})
    public void onViewClick(View view) {
        if (view.getId() == R.id.iv_back) {
            if (isChange) {
                showDilog();
            } else {
                finish();
                overridePendingTransition(0, R.anim.activity_exit);
            }
        }
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        if(processAdapter != null){
            processAdapter.destoryIat();
        }
        if (layoutUtils != null) {
            layoutUtils.onDestory();
        }
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            iv_back.performClick();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void iOnClickTakePicture(int index,String title,int imageIndex,String imageName,int imageNum,List<AloneImageAndRecordBean> imgList,boolean isWork) {
        this.titleIndex = index;
        this.imageIndex = imageIndex;
        this.imageName = imageName;
        this.title = title;
        if (imageNum >= 3) {
            return;
        }
        XXPermissions.with(X3NewProcessShowNewActivity.this)
                .permission(Manifest.permission.CAMERA)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if(all){
                            if (X3Utils.isFastClick()) {
                                if (photoDialog == null) {
                                    photoDialog = new X3SelectPhotoDialog(X3NewProcessShowNewActivity.this);
                                }
                                photoDialog.show();
                                photoDialog.setCurrentIndex(titleIndex);
                                photoDialog.setIonSelectOnclick(new X3SelectPhotoDialog.IonSelectOnclickListener() {

                                    @Override
                                    public void iOnselectFromReport() {//从检测报告
                                        if (aloneImageDialog == null) {
                                            aloneImageDialog = new X3BottomAloneImageDialog(X3NewProcessShowNewActivity.this);
                                            aloneImageDialog.setiOnClickAloneImage(X3NewProcessShowNewActivity.this);
                                        }
                                        aloneImageDialog.show();
                                        aloneImageDialog.setImgList(imgList);
                                        aloneImageDialog.showCarWork(carId,imageNum,index,imageIndex,isWork);
                                    }

                                    @Override
                                    public void iOnselectFromphotoOrCamera() {//拍照或者相册
                                        layoutUtils.startCamera(X3NewProcessShowNewActivity.this,rl_header,0,providerId(), 3 - imageNum, "",isWork, cameraBean -> onGetPictureOrVideo(cameraBean));

                                    }

                                    @Override
                                    public void iOnselectFromConstruction() {//施工报告
                                        showImageList(providerId(),false,imageNum,"",index,imageIndex, imgList,isWork);
                                    }
                                });


                            }
                        }else {
                            XXPermissions.startPermissionActivity(X3NewProcessShowNewActivity.this,permissions);
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        XXPermissions.startPermissionActivity(X3NewProcessShowNewActivity.this,permissions);
                    }
                });
    }


    @Override
    public void setNewRecAdapter(ProcessNewBean processNewMainBeans) {
        if (processNewMainBeans == null) {
            addAdapterList(new ArrayList<>(),new ArrayList<>(),null, "",0);
            return;
        }
        this.mainBean = processNewMainBeans;
        List<ProcessNewBean.ProcedureTempletEntityListDTO> entityList = processNewMainBeans.procedureTempletEntityList;
        List<ProcessNewBean.ServiceBaseShortBean> shortList = processNewMainBeans.serviceBaseShortList;
        if (X3StringUtils.isListEmpty(entityList)) {
            entityList = new ArrayList<>();
        }
        if (X3StringUtils.isListEmpty(shortList)) {
            shortList = new ArrayList<>();
        }

        addAdapterList(entityList,shortList,processNewMainBeans.workProcedureResourceEntity, X3StringUtils.isEmpty(processNewMainBeans.evaluation) ? "" : processNewMainBeans.evaluation,processNewMainBeans.evaluationSoundId);
        changeButton();
    }

    @Override
    public void getAwsSoundIdSuccess(AwsFileBean awsFileBean,int titleIndex,String title,int imageIndex,String imageName,String path,boolean isWork) {//图片回调
        if (awsFileBean == null) {
            return;
        }

        WorkNewImageBean imageBean;
        if (isWork) {
            imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + getProcessTitle(6) + imageName);

        }else {
            imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + title + imageName);
        }

        List<AloneImageAndRecordBean> addImageList = new ArrayList<>();
        addImageList.add(new AloneImageAndRecordBean(path,path,awsFileBean.id,1));
        addPhotoRefreshList(imageBean,addImageList,titleIndex,imageIndex,path,awsFileBean,isWork);
    }

    private void addRefreshList(WorkNewImageBean imageBean, List<AloneImageAndRecordBean> addImageList,int titleIndex,int imageIndex,boolean isWork) {
        List<AloneImageAndRecordBean> afterImageList;
        if (imageBean == null) {
            imageBean = new WorkNewImageBean();
            if (isWork) {
                imageBean.workKey = providerId() + workingProcedureName + getProcessTitle(6) + imageName;
            }else {
                imageBean.workKey = providerId() + workingProcedureName + title + imageName;
            }
            imageBean.imageList = addImageList;
            imageBean.workBaseId = providerId();
            afterImageList = addImageList;
            DaoSessionUtils.getInstance().insertWorkNewBean(imageBean);

        }else {
            List<AloneImageAndRecordBean> imageList = imageBean.getImageList();
            if (X3StringUtils.isListEmpty(imageList)) {
                imageList = new ArrayList<>();
            }
            imageList.addAll(addImageList);
            imageBean.imageList = imageList;
            afterImageList = imageList;
            DaoSessionUtils.getInstance().updateWorkNewBean(imageBean);
        }

        if (isWork) {
            imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName +  getProcessTitle(6) + imageName);
        }else {
            imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName +  title + imageName);
        }

        if (imageBean == null) {
            return;
        }
        refreshAdapter(afterImageList,titleIndex,imageIndex);

        changeButton();
        isChange = true;
        sbl_view.setIsBackToEnd(false);
    }

    private void addPhotoRefreshList(WorkNewImageBean imageBean, List<AloneImageAndRecordBean> addImageList,int titleIndex,int imageIndex,String path,AwsFileBean awsFileBean,boolean isWork) {
        List<AloneImageAndRecordBean> afterImageList;
        if (imageBean == null) {
            imageBean = new WorkNewImageBean();
            if (isWork) {
                imageBean.workKey = providerId() + workingProcedureName + getProcessTitle(6) + imageName;
            }else {
                imageBean.workKey = providerId() + workingProcedureName + title + imageName;
            }

            imageBean.imageList = addImageList;
            imageBean.workBaseId = providerId();
            afterImageList = addImageList;
            DaoSessionUtils.getInstance().insertWorkNewBean(imageBean);
        }else {
            int mCurrent = -1;
            List<AloneImageAndRecordBean> imageList = imageBean.getImageList();
            if (X3StringUtils.isListEmpty(imageList)) {
                imageList = new ArrayList<>();
            }
            for(int i = 0; i < imageList.size(); i++){
                if (imageList.get(i).getId() > 0){
                    if (imageList.get(i).getPath().equals(path) && imageList.get(i).getId() == awsFileBean.id) {
                        mCurrent = i;
                        break;
                    }
                } else {
                    if (imageList.get(i).getPath().equals(path)) {
                        mCurrent = i;
                        break;
                    }
                }
            }
            if(mCurrent == -1){
                return;
            }
            imageList.remove(mCurrent);
            imageList.add(mCurrent,new AloneImageAndRecordBean(path,path,awsFileBean.id,1));
            imageBean.imageList = imageList;
            afterImageList = imageList;
            DaoSessionUtils.getInstance().updateWorkNewBean(imageBean);
        }

        if (isWork) {
            imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName +  getProcessTitle(6) + imageName);
        }else {
            imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName +  title + imageName);
        }
        if (imageBean == null) {
            return;
        }
        refreshAdapter(afterImageList,titleIndex,imageIndex);

        changeButton();
        isChange = true;
        sbl_view.setIsBackToEnd(false);
    }

    private void changeButton() {
        //判断必选项 改变按钮
        WorkNewImageBean carimageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName +  getProcessTitle(0));
        if (carimageBean == null) {
            changeButtonStatus(false);
            return;
        }
        List<AloneImageAndRecordBean> carmageList = carimageBean.imageList;
        if (X3StringUtils.isListEmpty(carmageList)) {
            changeButtonStatus(false);
            return;
        }

        if (!isSelectProduce()) {
            // 施工过程情况没有做完
            changeButtonStatus(false);
            return;
        }

        if(isUpLoadSuccessOne(carmageList) && isUpLoadProcessSuccessOne()){
            changeButtonStatus(true);
        }else {
            changeButtonStatus(false);
        }

    }

    /**
     * 通过必选项 判断是否可以提交
     * @param isEnable
     */
    private void changeButtonStatus(boolean isEnable) {
        btn_commit.setBackground(isEnable ? ContextCompat.getDrawable(this,R.drawable.x3_alone_dialog_affirm2) : ContextCompat.getDrawable(this,R.drawable.x3_shape_rad_4_cor_d5d5));
    }

    private void addAdapterList(List<ProcessNewBean.ProcedureTempletEntityListDTO> entityList, List<ProcessNewBean.ServiceBaseShortBean> shortList, ProcessNewBean.WorkProcedureResourceEntityDTO workBaseBean, String evaluation,long evaluationSoundId) {
        List<ProgressListBean> mList = new ArrayList<>();
        //施工确认  产品确认 施工前情况 施工后情况 拆件确认
        for (int i = 0; i < 6;i++){
            ProgressListBean progressListBean = new ProgressListBean();
            progressListBean.title = getProcessTitle(i);
            progressListBean.urlList = getImageUrlList(workBaseBean,i);
            progressListBean.evaluation = getComment(i,evaluation);
            progressListBean.evaluationSoundId = getevaluationSoundId(i,evaluationSoundId);
            progressListBean.location = workBaseBean.carConfirmLocation;
            mList.add(progressListBean);
        }

        //施工过程情况本地缓存
        int customCount = 0;
        List<WorkNewImageBean> imageBeanList = DaoSessionUtils.getInstance().searchProcessBean(providerId() + workingProcedureName + getProcessTitle(6));

        if (!X3StringUtils.isListEmpty(imageBeanList)){
            List<ProcessNewBean.ProcedureTempletEntityListDTO> tmpPList = new ArrayList<>();

            for (int i = 0; i < imageBeanList.size(); i++) {
                WorkNewImageBean entity = imageBeanList.get(i);
                ProcessNewBean.ProcedureTempletEntityListDTO tmpDTO = new ProcessNewBean.ProcedureTempletEntityListDTO();
                tmpDTO.name = entity.name;
                tmpDTO.sn = entity.sn;
                tmpDTO.technicsSn = entity.technicsSn;
                tmpDTO.isCustomeProcess = entity.isCustomeProcess;
                tmpDTO.needPhoto = entity.needPhoto;
                tmpDTO.standardOrNot = entity.standardOrNot;
                if (!entity.standardOrNot){
                    customCount ++ ;
                }
                tmpDTO.imageList = X3StringUtils.isListEmpty(entity.imageList) ? new ArrayList<>() : entity.imageList;
                tmpPList.add(tmpDTO);
            }

            checkWorkProcessList(tmpPList,true);

            List<List<AloneImageAndRecordBean>> allList = new ArrayList<>();

            for (ProcessNewBean.ProcedureTempletEntityListDTO entityListDTO : tmpPList) {
                allList.add(X3StringUtils.isListEmpty(entityListDTO.imageList) ? new ArrayList<>() : entityListDTO.imageList);
            }

            ProgressListBean progressListBean = new ProgressListBean();
            progressListBean.title = getProcessTitle(6);
            progressListBean.pList = tmpPList;
            progressListBean.pImageList = allList;
            mList.add(3,progressListBean);

        } else {
            //施工过程情况
            if ((!X3StringUtils.isListEmpty(entityList) && standardOrNot)  || !standardOrNot) {
                List<List<AloneImageAndRecordBean>> allList = new ArrayList<>();
                for (int i = 0; i < entityList.size(); i++) {
                    ProcessNewBean.ProcedureTempletEntityListDTO procedureBean = entityList.get(i);
                    if (procedureBean == null) {
                        allList.add(new ArrayList<>());
                        continue;
                    }

                    WorkNewImageBean imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + getProcessTitle(6) + procedureBean.name + i);
                    if (imageBean == null) {
                        imageBean = new WorkNewImageBean();
                        imageBean.workKey = providerId() + workingProcedureName + getProcessTitle(6) + procedureBean.name + i;
                        imageBean.needPhoto = procedureBean.needPhoto;
                        imageBean.processKey = providerId() + workingProcedureName + getProcessTitle(6);
                        imageBean.name = procedureBean.name;
                        imageBean.sn = procedureBean.sn;
                        imageBean.technicsSn = procedureBean.technicsSn;
                        imageBean.isCustomeProcess = procedureBean.isCustomeProcess;
                        imageBean.standardOrNot = procedureBean.standardOrNot;
                        if (!imageBean.standardOrNot){
                            customCount ++ ;
                        }

                        List<ProcessNewBean.ProcedureTempletEntityListDTO.ImageTuple> mimeTupleList = procedureBean.mimeTupleList;
                        if (X3StringUtils.isListEmpty(mimeTupleList)) {
                            allList.add(new ArrayList<>());
                            imageBean.imageList = new ArrayList<>();
                        }else {
                            List<AloneImageAndRecordBean> imageList = new ArrayList<>();
                            for (int index = 0; index < mimeTupleList.size(); index++) {
                                ProcessNewBean.ProcedureTempletEntityListDTO.ImageTuple imageTuple = mimeTupleList.get(index);
                                if (imageTuple == null) {
                                    continue;
                                }
                                imageList.add(new AloneImageAndRecordBean(imageTuple.value,imageTuple.value,imageTuple.key,1));
                            }
                            allList.add(imageList);
                            imageBean.imageList = imageList;
                        }
                        imageBean.workBaseId = providerId();
                        DaoSessionUtils.getInstance().insertWorkNewBean(imageBean);

                    }else {
                        List<AloneImageAndRecordBean> initImageList = getInitImageList(imageBean.imageList);
                        imageBean.imageList = initImageList;
                        DaoSessionUtils.getInstance().updateWorkNewBean(imageBean);
                        allList.add(initImageList);
                    }
                }

                ProgressListBean progressListBean = new ProgressListBean();
                progressListBean.title = getProcessTitle(6);
                progressListBean.pList = entityList;
                progressListBean.pImageList = allList;
                mList.add(3,progressListBean);
            }
        }
        SpHelper.saveData(providerId() + workingProcedureName + getProcessTitle(6)+"",customCount);
        addCustomeCount = (int) SpHelper.getData(providerId() + workingProcedureName + getProcessTitle(6)+"",0);
        Log.e("sssssss","init  customCount = " + customCount);

        //选择题
        if ((!X3StringUtils.isListEmpty(shortList) && standardOrNot)  ) {//标准工序
            ProgressListBean progressListBean = new ProgressListBean();
            progressListBean.title = getProcessTitle(7);
            progressListBean.pList = entityList;
            progressListBean.serviceBaseShortList = getSortlList(shortList,7);
            mList.add(X3StringUtils.isListEmpty(entityList) ? 5 : 6,progressListBean);
        }else if(!X3StringUtils.isListEmpty(shortList) && !standardOrNot){//自定义工序
            ProgressListBean progressListBean = new ProgressListBean();
            progressListBean.title = getProcessTitle(7);
            progressListBean.pList = entityList;
            progressListBean.serviceBaseShortList = getSortlList(shortList,7);
            mList.add(6,progressListBean);
        }

        if (processAdapter != null && standardOrNot) {
            processAdapter.changeDate(mList,!X3StringUtils.isListEmpty(entityList),!X3StringUtils.isListEmpty(shortList));
        }else if(processAdapter != null && !standardOrNot){
            processAdapter.changeDate(mList,true,!X3StringUtils.isListEmpty(shortList));
        }

        sb_set.setChecked(false);
    }

    private long getevaluationSoundId(int i, long evaluationSoundId) {
        long  id ;
        WorkNewImageBean imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName +  getProcessTitle(i));
        if(imageBean == null){
            imageBean = new WorkNewImageBean();
            imageBean.workKey = providerId() + workingProcedureName + getProcessTitle(i);
            id = evaluationSoundId;
            imageBean.workBaseId = providerId();
            DaoSessionUtils.getInstance().insertWorkNewBean(imageBean);
        }else {
            id = imageBean.evaluationSoundId;
        }
        return id;

    }

    private String getComment(int i,String comment) {
        String commentStr = "";
        WorkNewImageBean imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName +  getProcessTitle(i));
        if(imageBean == null){
            imageBean = new WorkNewImageBean();
            imageBean.workKey = providerId() + workingProcedureName + getProcessTitle(i);
            imageBean.workComment = comment;
            commentStr = comment;
            imageBean.workBaseId = providerId();
            DaoSessionUtils.getInstance().insertWorkNewBean(imageBean);
        }else {
            commentStr = X3StringUtils.isEmpty(imageBean.workComment) ? "" : imageBean.workComment;
        }
        return commentStr;
    }

    /**
     * 获取的每项题目的图片
     * @param workBaseBean
     * @param i
     * @return
     */
    private List<AloneImageAndRecordBean> getImageUrlList(ProcessNewBean.WorkProcedureResourceEntityDTO workBaseBean, int i) {
        List<AloneImageAndRecordBean> imgList = new ArrayList<>();
        if (workBaseBean == null) {
            return imgList;
        }
        WorkNewImageBean imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId()  + workingProcedureName +  getProcessTitle(i));
        switch (i) {
            case 0:
                if (imageBean == null) {
                    imgList = getWorkNewImageTuple(workBaseBean.carConfirmMimeTupleList);
                    // TODO 插入数据
                    imageBean = new WorkNewImageBean();
                    imageBean.imageList = imgList;
                    imageBean.needPhoto = true;
                    imageBean.workKey = providerId() + workingProcedureName + getProcessTitle(i);
                    imageBean.workBaseId = providerId();
                    DaoSessionUtils.getInstance().insertWorkNewBean(imageBean);
                }else if(X3StringUtils.isListEmpty(imageBean.imageList)){
                    imgList = getWorkNewImageTuple(workBaseBean.carConfirmMimeTupleList);
                    imageBean.imageList = imgList;
                    DaoSessionUtils.getInstance().updateWorkNewBean(imageBean);

                } else {
                    List<AloneImageAndRecordBean> initImageList = getInitImageList(imageBean.imageList);
                    imageBean.imageList = initImageList;
                    DaoSessionUtils.getInstance().updateWorkNewBean(imageBean);
                    imgList = initImageList;
                }

                break;
            case 1:
                if (imageBean == null) {
                    imgList = getWorkNewImageTuple(workBaseBean.skuConfirmMimeTupleList);
                    imageBean = new WorkNewImageBean();
                    imageBean.imageList = imgList;
                    imageBean.workKey = providerId() + workingProcedureName + getProcessTitle(i);
                    imageBean.workBaseId = providerId();
                    DaoSessionUtils.getInstance().insertWorkNewBean(imageBean);
                }else {
                    List<AloneImageAndRecordBean> initImageList = getInitImageList(imageBean.imageList);
                    imageBean.imageList = initImageList;
                    DaoSessionUtils.getInstance().updateWorkNewBean(imageBean);
                    imgList = initImageList;
                }

                break;
            case 2:
                if (imageBean == null) {
                    imgList = getWorkNewImageTuple(workBaseBean.workBeforeMimeTupleList);
                    imageBean = new WorkNewImageBean();
                    imageBean.imageList = imgList;
                    imageBean.workKey = providerId() + workingProcedureName + getProcessTitle(i);
                    imageBean.workBaseId = providerId();
                    DaoSessionUtils.getInstance().insertWorkNewBean(imageBean);
                }else {
                    List<AloneImageAndRecordBean> initImageList = getInitImageList(imageBean.imageList);
                    imageBean.imageList = initImageList;
                    DaoSessionUtils.getInstance().updateWorkNewBean(imageBean);
                    imgList = initImageList;
                }

                break;
            case 3:
                if (imageBean == null) {
                    imgList = getWorkNewImageTuple(workBaseBean.workAfterMimeTupleList);
                    imageBean = new WorkNewImageBean();
                    imageBean.imageList = imgList;
                    imageBean.workKey = providerId() + workingProcedureName + getProcessTitle(i);
                    imageBean.workBaseId = providerId();
                    DaoSessionUtils.getInstance().insertWorkNewBean(imageBean);
                }else {
                    List<AloneImageAndRecordBean> initImageList = getInitImageList(imageBean.imageList);
                    imageBean.imageList = initImageList;
                    DaoSessionUtils.getInstance().updateWorkNewBean(imageBean);
                    imgList = initImageList;
                }
                break;
            case 4:
                if (imageBean == null) {
                    imgList = getWorkNewImageTuple(workBaseBean.dismantleConfirmMimeTupleList);
                    imageBean = new WorkNewImageBean();
                    imageBean.imageList = imgList;
                    imageBean.workKey = providerId() + workingProcedureName + getProcessTitle(i);
                    imageBean.workBaseId = providerId();
                    DaoSessionUtils.getInstance().insertWorkNewBean(imageBean);
                }else {
                    List<AloneImageAndRecordBean> initImageList = getInitImageList(imageBean.imageList);
                    imageBean.imageList = initImageList;
                    DaoSessionUtils.getInstance().updateWorkNewBean(imageBean);
                    imgList = initImageList;
                }
                break;
        }
        if (X3StringUtils.isListEmpty(imgList)) {
            imgList = new ArrayList<>();
        }

        return imgList;
    }

    /**
     * 进入页面的时候 如果之前有未上传成功的图片 需要将状态修改为异常状态
     * @param imageList
     * @return
     */
    private List<AloneImageAndRecordBean> getInitImageList(List<AloneImageAndRecordBean> imageList) {
        List<AloneImageAndRecordBean> afterList = new ArrayList<>();
        if (X3StringUtils.isListEmpty(imageList)) {
            return afterList;
        }
        for (int i = 0; i < imageList.size(); i++) {
            AloneImageAndRecordBean aloneBean = imageList.get(i);
            if (AloneUploadStatus.UPLODING == aloneBean.getUploadStatus()) {
                aloneBean.setUploadStatus(AloneUploadStatus.UPLOADING_FAILED);
            }
            afterList.add(aloneBean);
        }

        return afterList;
    }

    private List<ProcessNewBean.ServiceBaseShortBean> getSortlList(List<ProcessNewBean.ServiceBaseShortBean> shortList, int i) {
        List<ProcessNewBean.ServiceBaseShortBean> imgList = new ArrayList<>();
        if (shortList == null) {
            return imgList;
        }
        WorkNewImageBean imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName +  getProcessTitle(i));
        if(imageBean == null){
            imageBean = new WorkNewImageBean();
            imageBean.workKey = providerId() + workingProcedureName + getProcessTitle(i);
            imageBean.shortList = shortList;
            imgList = shortList;
            imageBean.workBaseId = providerId();
            DaoSessionUtils.getInstance().insertWorkNewBean(imageBean);
        }else {
            imgList = imageBean.shortList;
        }
        return imgList;
    }

    private List<AloneImageAndRecordBean> getWorkNewImageTuple(List<ProcessNewBean.ProcedureTempletEntityListDTO.ImageTuple> mimeTupleList) {
        List<AloneImageAndRecordBean> imgList = new ArrayList<>();
        if (X3StringUtils.isListEmpty(mimeTupleList)) {
            return imgList;
        }
        for (int index = 0; index < mimeTupleList.size(); index++) {
            ProcessNewBean.ProcedureTempletEntityListDTO.ImageTuple imageTuple = mimeTupleList.get(index);
            if (imageTuple == null) {
                continue;
            }
            imgList.add(new AloneImageAndRecordBean(imageTuple.value,imageTuple.value,imageTuple.key,1));
        }
        return imgList;
    }

    @Override
    public long providerId() {
        return getIntent().getLongExtra("workBaseId", 0L);
    }

    @Override
    public void saveWorkProceudreInfo() {
        X3ToastUtils.showMessage(getString(R.string.x3_submit_success));
        //保存成功
        finish();
        overridePendingTransition(0, R.anim.activity_exit);

    }

    @Override
    public void getVoiceAws(boolean isSuccess, AwsFileBean awsFileBean) {//语音上传完
        System.out.println("上传语音id");
        if(isSuccess && awsFileBean != null){
            long id = awsFileBean.id;
            WorkNewImageBean imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + getString(R.string.x3_user_comments));
            if(imageBean == null){
                imageBean = new WorkNewImageBean();
                imageBean.workKey = providerId() + workingProcedureName + getString(R.string.x3_user_comments);
                imageBean.evaluationSoundId = id;
                imageBean.workBaseId = providerId();
                DaoSessionUtils.getInstance().insertWorkNewBean(imageBean);
            }else {
                imageBean.evaluationSoundId =id;
                DaoSessionUtils.getInstance().updateWorkNewBean(imageBean);
            }
        }
    }

    private String getProcessTitle(int index) {
        switch (index) {
            case 0:
                return getString(R.string.x3_car_take_photo);
            case 1:
                return getString(R.string.x3_product_confirmation);
            case 2:
                return getString(R.string.x3_situation_before_construction);
            case 3:
                return getString(R.string.x3_situation_after_construction);
            case 4:
                return getString(R.string.situation_affirm);
            case 5:
                return getString(R.string.x3_user_comments);
            case 6:
                // 网络
                return getString(R.string.x3_situation_construction);
            case 7:
                return getString(R.string.situation_go_plan);
        }
        return "";
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetPictureOrVideo(CameraBean cameraBean) {
        if (cameraBean == null) {
            return;
        }
        switch ((int) cameraBean.resultCode) {
            //图片或者视频
            case X3Constent.CODE_CAMERA_REQUEST:
            case X3Constent.CODE_GALLERY_REQUEST:
                if (cameraBean.cameraData == null) {
                    return;
                }
                WorkNewImageBean imageBean;
                boolean isWork = cameraBean.isWork;
                if (isWork) {
                    imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + getProcessTitle(6) + imageName);

                }else {
                    imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + title + imageName);

                }
                List<AloneImageAndRecordBean> addImageList = new ArrayList<>();
                List<String> pList = (List<String>) cameraBean.cameraData;
                for (String path : pList) {
                    if (!X3StringUtils.isEmpty(path)) {
                        Log.e("up_load_","path =" + path);
                        addImageList.add(new AloneImageAndRecordBean(path,path,0,0));
                        mPresenter.uploadWavAws(new File(path), titleIndex, title, imageIndex, imageName, providerId(),path,isWork);//上传亚马逊
                    }
                }
                addRefreshList(imageBean,addImageList,titleIndex,imageIndex,isWork);
                break;
            default:
        }
    }

    /**
     * 获得新数据
     * @param imgList
     */
    private void refreshAdapter(List<AloneImageAndRecordBean> imgList,int tIndex,int sIndex) {
        if (processAdapter == null) {
            return;
        }
        List<ProgressListBean> mList = processAdapter.getmList();
        ProgressListBean progressListBean = mList.get(tIndex);
        if (sIndex == -1) {
            List<AloneImageAndRecordBean> urlList = imgList;
            if (X3StringUtils.isListEmpty(urlList)) {
                urlList = new ArrayList<>();
            }
            progressListBean.urlList = urlList;

        }else {
            List<List<AloneImageAndRecordBean>> pImageList = progressListBean.pImageList;
            if (X3StringUtils.isListEmpty(pImageList)) {
                pImageList = new ArrayList<>();
            }
            if (sIndex >= pImageList.size()) {
                return;
            }
            List<AloneImageAndRecordBean> imageAndRecordBeans = imgList;
            if (X3StringUtils.isListEmpty(imageAndRecordBeans)) {
                imageAndRecordBeans = new ArrayList<>();
            }
            pImageList.remove(sIndex);
            pImageList.add(sIndex,imageAndRecordBeans);
            progressListBean.pImageList = pImageList;
        }

        mList.remove(tIndex);
        mList.add(tIndex,progressListBean);

        if (processAdapter != null) {
            processAdapter.changeDate(mList,tIndex);
        }
    }

    @Override
    public void iOnClickSelectPlan(List<ProcessNewBean.ServiceBaseShortBean> shortBeans) {
        // 将多选题存储到数据库
        WorkNewImageBean imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId()  +  workingProcedureName +  getString(R.string.situation_go_plan));
        if(imageBean == null){
            imageBean = new WorkNewImageBean();
            imageBean.workKey = providerId()  + workingProcedureName + getString(R.string.situation_go_plan);
            imageBean.workBaseId = providerId();
            imageBean.shortList = X3StringUtils.isListEmpty(shortBeans) ? new ArrayList<>() : shortBeans;
            DaoSessionUtils.getInstance().insertWorkNewBean(imageBean);
        }else {
            imageBean.shortList = X3StringUtils.isListEmpty(shortBeans) ? new ArrayList<>() : shortBeans;
            DaoSessionUtils.getInstance().updateWorkNewBean(imageBean);
        }
        isChange = true;
        sbl_view.setIsBackToEnd(false);
    }

    @Override
    public void iOnClickComment(String comment) {//评论输入
//        System.out.println("当前的评论内容    "+comment);
        WorkNewImageBean imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + getString(R.string.x3_user_comments));
        if(imageBean == null){
            imageBean = new WorkNewImageBean();
            imageBean.workKey = providerId() + workingProcedureName + getString(R.string.x3_user_comments);
            imageBean.workComment = X3StringUtils.isEmpty(comment) ? "" : comment;
            imageBean.workBaseId = providerId();
            DaoSessionUtils.getInstance().insertWorkNewBean(imageBean);
        }else {
            imageBean.workComment = X3StringUtils.isEmpty(comment) ? "" : comment;
            DaoSessionUtils.getInstance().updateWorkNewBean(imageBean);
        }
        isChange = true;
        sbl_view.setIsBackToEnd(false);
    }

    @Override
    public void iOnClickVoice(File evaluaFile) {//上传语音
        System.out.println("上传语音1 "+ evaluaFile.length() + evaluaFile.getPath());
        if(mPresenter != null){
            System.out.println("上传语音");
            mPresenter.uploadVoiceAws(evaluaFile);
        }
    }

    @Override
    public void onScrollBottom() {
    new Handler().post(() ->linearLayoutManager.scrollToPositionWithOffset(processAdapter.getItemCount() - 1, Integer.MIN_VALUE));

    }

    @Override
    public void iOnShowButton(boolean isshow) {
        btn_commit.setVisibility(isshow ? View.VISIBLE : View.INVISIBLE);
    }

    @Override
    public void iOnClickAloneImage(AloneDetectionBean detectionBean,int imageNum,String title,int titleIndex,int imageIndex,List<AloneImageAndRecordBean> imgList,boolean isWork) {
        showImageList(detectionBean.id,true,imageNum,title,titleIndex,imageIndex,imgList,isWork);
    }

    private void showImageList(long id, boolean isAlone,int imageNum,String title,int titleIndex,int imageIndex,List<AloneImageAndRecordBean> imgList,boolean isWork) {
        numDialog = new X3BottomAloneImageNumDialog(this);
        numDialog.setiOnSelectImage(this);
        numDialog.show();
        numDialog.getImageList(3 - imageNum,id,isAlone,title,titleIndex,imageIndex,imgList,isWork);

    }

    @Override
    public void iOnSelectImage(List<AloneImageAndRecordBean> pathList,int titleIndex,int imageIndex,boolean isWork) {
        if(aloneImageDialog != null && aloneImageDialog.isShowing()){
            aloneImageDialog.dismiss();
        }
        // 选中相册中的图片
        WorkNewImageBean imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + title + imageName);
        addRefreshList(imageBean,pathList,titleIndex,imageIndex,isWork);
    }

    @Override
    public void iOnRemoveImage(AloneImageAndRecordBean aloneImageAndRecordBean, int titleIndex, int imageIndex,boolean isWork) {
        WorkNewImageBean imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + title + imageName);
        if(imageBean == null){
            return;
        }
        List<AloneImageAndRecordBean> imageList = imageBean.imageList;
        int curIndex = -1;
        if( imageList != null){
            for (int i = 0; i < imageList.size();i++){
                if(imageList.get(i).getId() == aloneImageAndRecordBean.getId()){
                    curIndex = i;
                }
            }
            if(curIndex != -1){
                imageList.remove(curIndex);
            }
            imageBean.imageList = imageList;
            DaoSessionUtils.getInstance().updateWorkNewBean(imageBean);
            WorkNewImageBean ib = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + title + imageName);
            addRefreshList(ib,new ArrayList<>(),titleIndex,imageIndex,isWork);
        }
    }

    //删除图片
    @Override
    public void iOnClickRemovePicture(int index, String title, int imageIndex, String imageTitle, int imageNum,int mPosition,boolean isWork) {//删除图片
        this.imageName = imageTitle;

        WorkNewImageBean imageBean;
        if (isWork) {
            imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + getProcessTitle(6) + imageTitle);

        }else {
            imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + title + imageTitle);

        }
        if(imageBean != null){
            List<AloneImageAndRecordBean> imageList = imageBean.imageList;
            if(X3StringUtils.isListEmpty(imageList)){
                imageList = new ArrayList<>();
            }
            if(mPosition < imageList.size()){
                imageList.remove(mPosition);
            }
            imageBean.imageList =imageList;
            DaoSessionUtils.getInstance().updateWorkNewBean(imageBean);

            if (isWork) {
                imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + getProcessTitle(6) + imageTitle);

            }else {
                imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName +  title + imageTitle);

            }
             if(imageBean == null){
                 return;
             }
            refreshAdapter(imageBean.imageList,index,imageIndex);
        }
        changeButton();
        isChange = true;
        sbl_view.setIsBackToEnd(false);
    }

    /**
     * true 可以提交被
     * @return
     */
    private boolean isSelectProduce() {
        //施工过程
        List<ProcessNewBean.ProcedureTempletEntityListDTO> procedureList = getDtoList();
        checkWorkProcessList(procedureList,false);
        if (!X3StringUtils.isListEmpty(procedureList)) {
            for (int i = 0; i < procedureList.size(); i++) {
                ProcessNewBean.ProcedureTempletEntityListDTO procedureBean = procedureList.get(i);
                boolean needPhoto = procedureBean.needPhoto;
                if (!needPhoto ) {
                    continue;
                }
                WorkNewImageBean workCurrentBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + getString(R.string.x3_situation_construction) + procedureBean.name+i);
                if (workCurrentBean == null) {
                    return false;
                }
                if(X3StringUtils.isListEmpty(workCurrentBean.imageList)){
                    //TODO
                    return false;
                }
            }
        }
        return true;
    }

    /**
     *
     */
    public boolean isUpLoadSuccessOne( List<AloneImageAndRecordBean> carmageList){
        for (int i = 0; i < carmageList.size();i++){//必选项   每一道题 图片只要有一张 上传成功了就高亮
            if(carmageList.get(i).getUploadStatus() == 1){
                return true;
            }
        }
        return false;
    }
    private boolean isUpLoadProcessSuccessOne() {
        //施工过程
        List<ProcessNewBean.ProcedureTempletEntityListDTO> procedureList = getDtoList();
        checkWorkProcessList(procedureList,false);
        if (!X3StringUtils.isListEmpty(procedureList)) {
            for (int i = 0; i < procedureList.size(); i++) {
                ProcessNewBean.ProcedureTempletEntityListDTO procedureBean = procedureList.get(i);
                boolean needPhoto = procedureBean.needPhoto;
                if (!needPhoto) {
                    continue;
                }
                WorkNewImageBean workCurrentBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + getString(R.string.x3_situation_construction) + procedureBean.name + i);
                if (workCurrentBean == null){
                    return false;
                }
                List<AloneImageAndRecordBean> imageList = workCurrentBean.imageList;
                if (imageList == null){
                    return false;
                }
                boolean upLoadSuccessOne = isUpLoadSuccessOne(imageList);
                return  upLoadSuccessOne ? true : false;
            }
        }
        return true;
    }
    
    @Override
    public void iOnAgainUploadImage(String path, int titleIndex,String title,int imageIndex,String imageTitle,int imageNum,List<AloneImageAndRecordBean> imgList,boolean isWork) {
        this.imageName = imageTitle;
        if (mPresenter != null) {
            mPresenter.uploadWavAws(new File(path), titleIndex, title, imageIndex, imageTitle, providerId(),path,isWork);//上传亚马逊
        }
    }

    @Override
    public void iOnDeleteImage(int titleIndex, List<AloneImageAndRecordBean> mList,String imageName,boolean isWork) {
        WorkNewImageBean imageBean;
        if (isWork) {
            imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + getProcessTitle(6) + imageName);
        }else {
            imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName +  getProcessTitle(titleIndex));
        }

        if(imageBean == null){
            imageBean = new WorkNewImageBean();
            imageBean.imageList = mList;
            imageBean.workKey = providerId() + workingProcedureName + getProcessTitle(titleIndex);
            imageBean.workBaseId = providerId();
            DaoSessionUtils.getInstance().insertWorkNewBean(imageBean);
        }else {
            imageBean.imageList = mList;
            DaoSessionUtils.getInstance().updateWorkNewBean(imageBean);
        }
    }

    @Override
    public void iOnGetLocation() {//获取位置
        if(isFinishing()){
            if(fusedLocationUtils != null){
                fusedLocationUtils.onDestory();
            }
            return;
        }
        if (fusedLocationUtils != null) {
            fusedLocationUtils.startLocation();
        }
    }

    @Override
    public void iOnGetLocationSuccess(String locationBean) {
        System.out.println("定位"+ locationBean);
        if (isFinishing()) {
            if (fusedLocationUtils != null) {
                fusedLocationUtils.onDestory();
            }
            return;
        }
        if (X3StringUtils.isEmpty(locationBean)) {
            return;
        }
        if (fusedLocationUtils != null) {
            fusedLocationUtils.onDestory();
        }
        WorkNewImageBean imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + getProcessTitle(0));
        if (imageBean == null) {
            imageBean = new WorkNewImageBean();
            imageBean.workKey = providerId() + workingProcedureName + getProcessTitle(0);
            imageBean.location = locationBean;
            imageBean.imageList = new ArrayList<>();
            imageBean.workBaseId = providerId();
            DaoSessionUtils.getInstance().insertWorkNewBean(imageBean);
        }else {
            imageBean.location = locationBean;
            DaoSessionUtils.getInstance().updateWorkNewBean(imageBean);
        }

        if (processAdapter == null) {
            return;
        }
        List<ProgressListBean> list = processAdapter.getmList();
        if (X3StringUtils.isListEmpty(list)) {
            return;
        }
        ProgressListBean progressListBean = list.get(0);
        progressListBean.location = locationBean;
        list.remove(0);
        list.add(0,progressListBean);
        processAdapter.changeLocation(list,2);
    }

    @Override
    public void iOnGetLocationFailed() {
        if (isFinishing()) {
            fusedLocationUtils.onDestory();
            return;
        }
        if (rlv_work.getScrollState() == RecyclerView.SCROLL_STATE_IDLE
                && (rlv_work.isComputingLayout() == false)) {
            if (processAdapter != null) {
                processAdapter.changeLocation(1);
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_commit) {//提交
            if (!X3Utils.isFastClick()) {
                return;
            }
            if (processAdapter != null && processAdapter.isListening()) {
                //正在听写
                return;
            }

            commitData();
        }
    }

    private void commitData() {
        if (mainBean == null) {
            return;
        }
        WorkNewImageBean imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + getProcessTitle(0));
        if (imageBean == null) {
            return;
        }
        List<AloneImageAndRecordBean> imageList = imageBean.imageList;
        if(X3StringUtils.isListEmpty(imageList)){
            // TODO 第一项不能为空 必须上传图片
            X3ToastUtils.showMessage(getString(R.string.complete_required_content_first));
            return;
        }
        if(!isUpLoadSuccessOne(imageList)){//产品确认 正在上传图片
            return;
        }

        //施工过程
        List<ProcessNewBean.ProcedureTempletEntityListDTO> procedureList = getDtoList();
        checkWorkProcessList(procedureList,false);
        if (!X3StringUtils.isListEmpty(procedureList)) {
            for (int i = 0; i < procedureList.size(); i++) {
                ProcessNewBean.ProcedureTempletEntityListDTO procedureBean = procedureList.get(i);
                boolean needPhoto = procedureBean.needPhoto;
                WorkNewImageBean workCurrentBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + getString(R.string.x3_situation_construction) + procedureBean.name + i);

                if (workCurrentBean == null) {
                    continue;
                }
                if(needPhoto && X3StringUtils.isListEmpty(workCurrentBean.imageList)){
                    //TODO
                    X3ToastUtils.showMessage(getString(R.string.complete_required_content_first));
                    return;
                }

                procedureBean.resourceIdList = getResourceList(workCurrentBean.getImageList());
                procedureList.remove(i);
                procedureList.add(i,procedureBean);
            }
        }
        mainBean.procedureTempletEntityList = procedureList;
        if(!isUpLoadProcessSuccessOne()){//施工报告 正在上传图片
            return;
        }

        //本地五条数据
        ProcessNewBean.WorkProcedureResourceEntityDTO workBean = mainBean.workProcedureResourceEntity;
        WorkNewImageBean carConfirmBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName +  getProcessTitle(0));
        workBean.carConfirmLocation = carConfirmBean.location;
        workBean.carConfirmResourceIdList = getResourceList(carConfirmBean.imageList);

        WorkNewImageBean skuBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + getProcessTitle(1));
        workBean.skuConfirmResourceIdList = getResourceList(skuBean.imageList);

        WorkNewImageBean workBeforeBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + getProcessTitle(2));
        workBean.workBeforeResourceIdList = getResourceList(workBeforeBean.imageList);

        WorkNewImageBean workAfterBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + getProcessTitle(3));
        workBean.workAfterResourceIdList = getResourceList(workAfterBean.imageList);

        WorkNewImageBean dismantleBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + getProcessTitle(4));
        workBean.dismantleConfirmResourceIdList = getResourceList(dismantleBean.imageList);

        mainBean.workProcedureResourceEntity = workBean;

        // 履行保养计划
        WorkNewImageBean planBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + getString(R.string.situation_go_plan));
        mainBean.serviceBaseShortList = (planBean == null) ? new ArrayList<>() : planBean.shortList;

        //评论
        WorkNewImageBean commentBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName +  getString(R.string.x3_user_comments));
        mainBean.evaluation = commentBean.workComment;
        mainBean.evaluationSoundId = commentBean.evaluationSoundId;

        if(mPresenter != null){
            mPresenter.saveWorkProceudreInfo(mainBean);
        }
    }

    private List<ProcessNewBean.ProcedureTempletEntityListDTO> getDtoList(){
        List<ProcessNewBean.ProcedureTempletEntityListDTO> procedureList = null;
        List<WorkNewImageBean> imageBeanList = DaoSessionUtils.getInstance().searchProcessBean(providerId() + workingProcedureName + getProcessTitle(6));
        if (!X3StringUtils.isListEmpty(imageBeanList)){
            List<ProcessNewBean.ProcedureTempletEntityListDTO> tmpPList = new ArrayList<>();

            for (int i = 0; i < imageBeanList.size(); i++) {
                WorkNewImageBean entity = imageBeanList.get(i);
                ProcessNewBean.ProcedureTempletEntityListDTO tmpDTO = new ProcessNewBean.ProcedureTempletEntityListDTO();
                tmpDTO.name = entity.name;
                tmpDTO.sn = entity.sn;
                tmpDTO.technicsSn = entity.technicsSn;
                tmpDTO.isCustomeProcess = entity.isCustomeProcess;
                tmpDTO.needPhoto = entity.needPhoto;
                tmpDTO.standardOrNot = entity.standardOrNot;
                tmpDTO.imageList = X3StringUtils.isListEmpty(entity.imageList) ? new ArrayList<>() : entity.imageList;
                tmpPList.add(tmpDTO);
            }
            procedureList = tmpPList;

        } else {
            procedureList = mainBean.procedureTempletEntityList;
        }
        return procedureList;
    }

    private List<Long> getResourceList(List<AloneImageAndRecordBean> mList) {
        List<Long> idList = new ArrayList<>();
        if (X3StringUtils.isListEmpty(mList)) {
            return idList;
        }
        for (AloneImageAndRecordBean imageAndRecordBean : mList) {
            idList.add(imageAndRecordBean.getId());
        }
        return idList;
    }

    public  void showDilog(){
        if (backDialog == null) {
            backDialog = new X3PointDialog(this, "", getString(R.string.submit_modified_information), getString(R.string.x3_no_tips), getString(R.string.x3_yes_tips));
        }
        backDialog.show();
        backDialog.setiBtnClick(new X3PointDialog.IBtnClick() {
            @Override
            public void iBtnAffirmClick() {
                commitData();
            }

            @Override
            public void iBtnCancelClick() {
                finish();
                overridePendingTransition(0, R.anim.activity_exit);
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("施工工艺页");
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("施工工艺页");
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // 切换显示必填还是非必填
        isShowRequired = isChecked;
        if (processAdapter != null) {
            processAdapter.changeShowRequired(isShowRequired);
        }
    }

    private int addCustomeCount = 0;

    @Override
    public void iOnClickAddProcess() {
        addCustomeCount = (int) SpHelper.getData(providerId() + workingProcedureName + getProcessTitle(6)+"",0);
        Log.e("sssssss","iOnClickAddProcess addCustomeCount = " + addCustomeCount);
        if (addCustomeCount >= 100){
            X3ToastUtils.showMessage(getString(R.string.x3_construction_process_count_limit));
            return;
        }

        X3BottomInputProcessNameDialog nameDialog = new X3BottomInputProcessNameDialog(this);
        nameDialog.setAdjustInputMethod(true)
                .setBackPressEnable(true)
                .setAutoShowInputMethod(nameDialog.findViewById(R.id.ed_input), false)
                .setAdjustInputMode(R.id.ed_input, BasePopupWindow.FLAG_KEYBOARD_ALIGN_TO_ROOT | BasePopupWindow.FLAG_KEYBOARD_ANIMATE_ALIGN)
                .showPopupWindow();
        nameDialog.setIOnClickOk(this);
    }

    @Override
    public void iOnClickOk(String content) {
        //添加工序

        changeButtonStatus(false);

        List<ProgressListBean> mList = processAdapter.getmList();
        if (X3StringUtils.isListEmpty(mList)) {
            return;
        }

        ProgressListBean progressListBean = mList.get(3);

        List<ProcessNewBean.ProcedureTempletEntityListDTO> pList = progressListBean.pList;
        if (X3StringUtils.isListEmpty(pList)) {
            pList = new ArrayList<>();
        }

        checkWorkProcessList(pList,false);

        int count = ++addCustomeCount ;
        Log.e("sssssss","iOnClickOk  ++addCustomeCount = " + count);
        WorkNewImageBean imageBean = new WorkNewImageBean();
        imageBean.workKey = providerId() + workingProcedureName + getProcessTitle(6) + content + pList.size();
        imageBean.processKey = providerId() + workingProcedureName + getProcessTitle(6);
        imageBean.sn = mainBean.technicTempletSn + "_"+System.currentTimeMillis();
        imageBean.technicsSn = mainBean.technicTempletSn + "__"+System.currentTimeMillis();
        imageBean.isCustomeProcess = true;
        imageBean.needPhoto = true;
        imageBean.imageList = new ArrayList<>();
        imageBean.workBaseId = providerId();
        imageBean.name = content ;
        imageBean.customeCount = count;

        DaoSessionUtils.getInstance().insertWorkNewBean(imageBean);

        ProcessNewBean.ProcedureTempletEntityListDTO entityListDTO = new ProcessNewBean.ProcedureTempletEntityListDTO();
        entityListDTO.name = content;
        entityListDTO.sn = mainBean.technicTempletSn + "_" + System.currentTimeMillis();
        entityListDTO.technicsSn = mainBean.technicTempletSn + "__" + System.currentTimeMillis();
        entityListDTO.isCustomeProcess = true;
        entityListDTO.needPhoto = true;
        entityListDTO.standardOrNot = false;
        entityListDTO.imageList = new ArrayList<>();
        pList.add(entityListDTO);

        List<List<AloneImageAndRecordBean>> allList = new ArrayList<>();

        List<WorkNewImageBean> imageBeanList = DaoSessionUtils.getInstance().searchProcessBean(providerId() + workingProcedureName + getProcessTitle(6));

        if (X3StringUtils.isListEmpty(imageBeanList)) {
            return;
        }

        for (int i = 0; i < pList.size(); i++) {
            String name = pList.get(i).name;
            WorkNewImageBean imageBean1 = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + getProcessTitle(6) + name + i);
            allList.add(X3StringUtils.isListEmpty(imageBean1.imageList) ? new ArrayList<>() : imageBean1.imageList);
        }

        progressListBean.pList = pList;
        progressListBean.pImageList = allList;
        mList.remove(3);
        mList.add(3, progressListBean);
        int processIndex = 3;
        if (processAdapter != null) {
            processAdapter.changeDate(mList, processIndex);
        }
        SpHelper.saveData(providerId() + workingProcedureName + getProcessTitle(6)+"",count);

    }

    private void checkWorkProcessList(List<ProcessNewBean.ProcedureTempletEntityListDTO> pList,boolean isStart) {
        if (X3StringUtils.isListEmpty(pList)) {
            return;
        }
        if (pList.size() == 1 && X3StringUtils.isEmpty(pList.get(0).name) && isStart) {
            return;
        }

        Iterator<ProcessNewBean.ProcedureTempletEntityListDTO> iterator = pList.iterator();
        while (iterator.hasNext()) {
            ProcessNewBean.ProcedureTempletEntityListDTO next = iterator.next();
            if (X3StringUtils.isEmpty(next.name)) {
                iterator.remove();
            }
        }
    }

    @Override
    public void iOnClickOk(String content,int index) {
        List<ProgressListBean> mList = processAdapter.getmList();

        WorkNewImageBean imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + getProcessTitle(6) + oldName + index);
        if (imageBean == null){
            return;
        }
        imageBean.name = content ;
        imageBean.workKey = providerId() + workingProcedureName + getProcessTitle(6) + content + index;
        DaoSessionUtils.getInstance().updateWorkNewBean(imageBean);

        List<ProcessNewBean.ProcedureTempletEntityListDTO> tmpPList = new ArrayList<>();

        ProgressListBean progressListBean = mList.get(3);
        tmpPList = progressListBean.pList;
        if (tmpPList != null && tmpPList.size() > index){
            ProcessNewBean.ProcedureTempletEntityListDTO dto = tmpPList.get(index);
            dto.name = content;
            tmpPList.remove(index);
            tmpPList.add(index,dto);
        }
        progressListBean.pList = tmpPList;
        mList.remove(3);
        mList.add(3,progressListBean);

        int processIndex = 3;
        if (processAdapter != null) {
            processAdapter.changeDate(mList, processIndex);
        }
    }
    private String oldName = "";
    @Override
    public void iOnClickTitle(int index, String name) {
        oldName = name;
        X3BottomInputProcessNameDialog nameDialog = new X3BottomInputProcessNameDialog(this);
        nameDialog.setOldName(name);
        nameDialog.setModify(true);
        nameDialog.setModifyIndex(index);
        nameDialog.setAdjustInputMethod(true)
                .setBackPressEnable(true)
                .setAutoShowInputMethod(nameDialog.findViewById(R.id.ed_input), false)
                .setAdjustInputMode(R.id.ed_input, BasePopupWindow.FLAG_KEYBOARD_ALIGN_TO_ROOT | BasePopupWindow.FLAG_KEYBOARD_ANIMATE_ALIGN)
                .showPopupWindow();
        nameDialog.setIOnClickOk(this);
    }

    @Override
    public void inOnClickDelete(String imageName,boolean isHavePicture) {
        if (isHavePicture) {
            if (delDialog == null) {
                delDialog = new X3PointDialog(this,"",getString(R.string.x3_construction_process_delete_tips),getString(R.string.x3_cancel_info), getString(R.string.x3_affirm_info));
            }
            delDialog.show();
            delDialog.setRightClick(v -> {
                delDialog.dismiss();
                deleteProcess(imageName);
            });
            return;
        }
        deleteProcess(imageName);
        changeButton();
    }

    private void deleteProcess(String imageName) {
        //delete工序
        WorkNewImageBean imageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerId() + workingProcedureName + getProcessTitle(6) + imageName);
        if (imageBean == null) {
            return;
        }
        DaoSessionUtils.getInstance().deleteWorkNewBean(imageBean);

        List<ProgressListBean> progressListBeans = refreshWorkProcess();

        int processIndex = 3;
        if (processAdapter != null) {
            processAdapter.changeDate(progressListBeans, processIndex);
        }

        int count = --addCustomeCount;
        if (count < 0) {
            count = 0;
        }
        SpHelper.saveData(providerId() + workingProcedureName + getProcessTitle(6) + "", count);
        Log.e("sssssss","  deleteProcess = " + count);

    }

    private List<ProgressListBean> refreshWorkProcess() {
        List<WorkNewImageBean> imageBeanList = DaoSessionUtils.getInstance().searchProcessBean(providerId() + workingProcedureName + getProcessTitle(6));

        List<ProcessNewBean.ProcedureTempletEntityListDTO> pList = new ArrayList<>();
        List<List<AloneImageAndRecordBean>> allList = new ArrayList<>();

        Iterator<WorkNewImageBean> iterator = imageBeanList.iterator();
        while (iterator.hasNext()) {
            WorkNewImageBean entity = iterator.next();
            if (entity == null || X3StringUtils.isEmpty(entity.name)) {
                iterator.remove();
            }
        }

        if (X3StringUtils.isListEmpty(imageBeanList)) {
            ProcessNewBean.ProcedureTempletEntityListDTO tmpDTO = new ProcessNewBean.ProcedureTempletEntityListDTO();
            tmpDTO.name = "";
            tmpDTO.sn = mainBean.technicTempletSn;
            tmpDTO.technicsSn = mainBean.technicTempletSn;
            tmpDTO.isCustomeProcess = false;
            tmpDTO.needPhoto = false;
            tmpDTO.standardOrNot = false;
            tmpDTO.imageList = new ArrayList<>();
            pList.add(tmpDTO);
            allList.add(new ArrayList<>());

        }else {
            for (int i = 0; i < imageBeanList.size(); i++) {
                WorkNewImageBean entity = imageBeanList.get(i);
                ProcessNewBean.ProcedureTempletEntityListDTO tmpDTO = new ProcessNewBean.ProcedureTempletEntityListDTO();
                tmpDTO.name = entity.name;
                tmpDTO.sn = entity.sn;
                tmpDTO.technicsSn = entity.technicsSn;
                tmpDTO.isCustomeProcess = entity.isCustomeProcess;
                tmpDTO.needPhoto = entity.needPhoto;
                tmpDTO.standardOrNot = entity.standardOrNot;
                tmpDTO.imageList = X3StringUtils.isListEmpty(entity.imageList) ? new ArrayList<>() : entity.imageList;
                pList.add(tmpDTO);

                // 删除之后 下标变化需要改动workKey
                entity.workKey = providerId() + workingProcedureName + getProcessTitle(6) + entity.name + i;
                DaoSessionUtils.getInstance().updateWorkNewBean(entity);
            }

            checkWorkProcessList(pList,true);

            for (ProcessNewBean.ProcedureTempletEntityListDTO entityListDTO : pList) {
                allList.add(X3StringUtils.isListEmpty(entityListDTO.imageList) ? new ArrayList<>() : entityListDTO.imageList);
            }
        }

        List<ProgressListBean> mList = processAdapter.getmList();
        ProgressListBean progressListBean = mList.get(3);
        progressListBean.pList = pList;
        progressListBean.pImageList = allList;
        mList.remove(3);
        mList.add(3, progressListBean);
        return mList;
    }

}


